<template>
  <div class="file-table-wrapper">
    <!-- 文件表格 -->
    <a-table
      class="file-table"
      :class="'file-type-' + fileType().current()"
      ref="multipleTable"
      fit
      :loading="loading"
      rowKey="id"
      tooltip-effect="dark"
      :dataSource="fileList"
      :pagination="false"
      :columns="columns"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    >
      <template slot="fileImage" slot-scope="text, record, index">
        <img :src="setFileImg(record)" style="height: 30px"/>
      </template>
      <template slot="fileName" slot-scope="text, record, index">
        <div style="cursor:pointer;" @click="clickFileName(record)">
          {{ filenameComplete(record) }}
        </div>
      </template>
      <template slot="fileType" slot-scope="text,record,index">
        <span v-if="record.extension">{{ record.extension }}</span>
        <span v-else>文件夹</span>
      </template>
      <template slot="fileSize" slot-scope="text,record,index">
        <div style="padding: 0 10px;">{{ calculateFileSize(record.fileSize) }}</div>
      </template>
      <span slot="action" slot-scope="text, record" v-show="has">
          <a @click="getDownloadPath(record)" v-if="checkHasPermission(record)">下载</a>

          <a-divider type="vertical"/>

          <a-dropdown >
            <a class="ant-dropdown-link">
              更多 <a-icon type="down"/>
            </a>
            <a-menu slot="overlay">
<!--              <a-menu-item>-->
              <!--                <a href="javascript:;" @click="handleDetail(record)">详情</a>-->
              <!--              </a-menu-item>-->

              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>

               <a-menu-item v-show="fileType().isRecycle()">
                <a href="javascript:;" @click="recoverFileBtn(record)">恢复</a>
              </a-menu-item>

              <!--              <a-menu-item v-show="fileType().isNotRecycle()">-->
              <!--                <a href="javascript:;" @click="showMoveFileDialog(record)">移动</a>-->
              <!--              </a-menu-item>-->
              <a-menu-item v-show="fileType().isNotRecycle()">
                <a href="javascript:;" @click="renameFile(record)">重命名</a>
              </a-menu-item>

              <a-menu-item v-show="checkHasPermission(record)">
                 <a href="javascript:;" style="display: block;color: inherit;" @click="getDownloadPath(record)"
                    :download="record.filename + '.' + record.extension">下载</a>
              </a-menu-item>


            </a-menu>
          </a-dropdown>
        </span>

      <!--      <template slot="action" slot-scope="text,scope,index">-->
      <!--          <a-dropdown trigger="click" >-->
      <!--            <a-button size="mini">-->
      <!--              操作-->
      <!--              <i class="a-icon-arrow-down a-icon&#45;&#45;right"></i>-->
      <!--            </a-button>-->
      <!--            <a-dropdown-menu slot="dropdown">-->
      <!--              <a-dropdown-item @click.native="deleteFileBtn(scope)">删除</a-dropdown-item>-->
      <!--              <a-dropdown-item @click.native="recoverFileBtn(scope)" v-show="fileType().isRecycle()">恢复-->
      <!--              </a-dropdown-item>-->
      <!--              <a-dropdown-item @click.native="showMoveFileDialog(scope)" v-show="fileType().isNotRecycle()">移动-->
      <!--              </a-dropdown-item>-->
      <!--              <a-dropdown-item @click.native="renameFile(scope)" v-show="fileType().isNotRecycle()">重命名-->
      <!--              </a-dropdown-item>-->
      <!--              &lt;!&ndash;              <a-dropdown-item&ndash;&gt;-->
      <!--              &lt;!&ndash;                  v-if="scope.row.extension === 'zip' && fileType().isNotRecycle()"&ndash;&gt;-->
      <!--              &lt;!&ndash;                  @click.native="unzipFile(scope.row)">解压缩&ndash;&gt;-->
      <!--              &lt;!&ndash;              </a-dropdown-item>&ndash;&gt;-->
      <!--              <a-dropdown-item v-show="scope.dir == false && fileType().isNotRecycle()">-->
      <!--                <a-->
      <!--                    target="_blank"-->
      <!--                    style="display: block;color: inherit;"-->
      <!--                    :href="getDownloadPath(scope.id)"-->
      <!--                    :download="scope.filename + '.' + scope.extension">下载</a>-->
      <!--              </a-dropdown-item>-->
      <!--            </a-dropdown-menu>-->
      <!--          </a-dropdown>-->
      <!--        </template>-->
    </a-table>
    <!--    新建文件夹-->
    <DepartFileRename ref="rename" @ok="renameSuccess" :file-info="renameFileInfo"></DepartFileRename>
  </div>
</template>

<script>
import {
  unzipfile,
  deleteDepartFile,
  renameFile,
  deleteRecoveryFile,
  recoverRecycleFile,
  getDownloadDepartFile
} from '@/api/file.js'
// import {dowmloadFile} from '@/api/manage'
import {mapGetters} from 'vuex'
import {filenameSplit} from "@/views/filemanage/filters";
import DepartFileRename from "./DepartFileRename";
import SelectColumn from "./SelectColumn";
import Mkdir from "./Mkdir";
import {getFileAccessHttpUrl} from '@/api/manage';
import Vue from "vue";

const columns = [
  {
    title: '',
    dataIndex: 'dir',
    scopedSlots: {customRender: 'fileImage'},


  },
  {
    title: '文件名',
    dataIndex: 'fileName',
    sorter: true,
    sortDirections: ['descend', 'ascend'],
    scopedSlots: {customRender: 'fileName'},
  },
  {
    title: '文件大小',
    dataIndex: 'fileSize',
    sorter: true,
    scopedSlots: {customRender: 'fileSize'},
    sortDirections: ['descend', 'ascend'],
  },
  {
    title: '文件类型',
    dataIndex: 'extension',
    sorter: true,
    scopedSlots: {customRender: 'fileType'},
    sortDirections: ['descend', 'ascend'],
  },
  {
    title: '上传日期',
    dataIndex: 'createTime',
    sorter: true,
    sortDirections: ['descend', 'ascend'],
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: {customRender: 'action'},
    align: "center",
    width: 170
  }
];
export default {
  name: 'DepartFileTable',
  props: {
    fileList: Array,  //  文件列表
    loading: Boolean,
    has: Boolean,
  },
  components: {
    DepartFileRename
  },
  data() {
    return {
      //  移动文件模态框数据
      columns,
      selectedRowKeys: [],
      dialogMoveFile: {
        isBatchMove: false,
        visible: false, //  是否可见
        fileTree: [], //  目录树
        defaultProps: {
          children: 'children',
          label: 'label'
        }
      },
      viewFilePath: '',
      renameFileInfo: null
    }
  },
  methods: {
    checkHasPermission(record) {

      return record.dir == false && this.fileType().isNotRecycle() && this.has;

    }
    ,
    handleDetail(fileInfo) {

    },
    handleDelete(fileInfo) {
      this.confirmDeleteFile(fileInfo, this.fileType().isRecycle())
    },

    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },
    filenameComplete(item) {
      return item.fileName + (!item.dir && item.extension !== null ? `.${item.extension}` : '')
    },
    getDownloadPath(fileInfo) {
      getDownloadDepartFile(fileInfo.id).then(res => {
        if (res.success) {
          location.href = getFileAccessHttpUrl(res.result);
        }else{
          this.$message.error(res.message);
        }
      });


    },
    /**
     * 表格数据获取相关事件
     */
    //  根据文件扩展名设置文件图片
    setFileImg(row) {
      if (!row.extension) {
        //  文件夹
        return this.FILE_IMG_MAP.dir
      } else if (!this.FILE_IMG_TYPE_LIST.includes(row.extension)) {
        //  无法识别文件类型的文件
        return this.FILE_IMG_MAP.unknown
      } else if (['jpg', 'png', 'jpeg', 'gif'].includes(row.extension)) {
        // 图片类型，直接显示缩略图
        return this.FILE_IMG_MAP.img
      } else {
        //  可以识别文件类型的文件
        return this.FILE_IMG_MAP[row.extension]
      }
    },
    //  计算文件大小
    calculateFileSize(size) {
      const B = 1024
      const KB = Math.pow(1024, 2)
      const MB = Math.pow(1024, 3)
      const GB = Math.pow(1024, 4)
      if (!size) {
        return '_'
      } else if (size < KB) {
        return (size / B).toFixed(0) + 'KB'
      } else if (size < MB) {
        return (size / KB).toFixed(1) + 'MB'
      } else if (size < GB) {
        return (size / MB).toFixed(2) + 'GB'
      } else {
        return (size / GB).toFixed(3) + 'TB'
      }
    },

    //  点击文件名
    clickFileName(row) {
      //  若是目录则进入目录
      if (row.dir) {
        this.$emit("getTableDataByTypeAndPath", row.id)

      }
      //  若是文件，则进行相应的预览
      else {
        //  若当前点击项是图片
        if (this.IMG_TYPE_LIST.includes(row.extension)) {
          let data = {
            imgReviewVisible: true,
            imgReviewList: [
              {
                id: row.id,
                fileUrl: this.getDownloadPath(row.id),
                downloadLink: this.getDownloadPath(row.id),
                filename: row.filename,
                extension: row.extension
              }
            ],
            activeIndex: 0
          }
          this.$store.commit('setImgReviewData', data)
        }
        //  若当前点击项是可以使用office在线预览的
        if (['ppt', 'pptx', 'doc', 'docx', 'xls', 'xlsx'].includes(row.extension)) {
          // window.open(this.getFileOnlineViewPathByOffice(row.id), '_blank')
          window.open(this.getDownloadPath(row.id), '_blank')
        }
        //  若当前点击项是pdf
        if (row.extension === 'pdf') {
          window.open(this.getDownloadPath(row.id), '_blank')
        }
        //  若当前点击项是html、js、css、json
        const CODE = ['html', 'js', 'css', 'json']
        if (CODE.includes(row.extension)) {
          window.open(this.getDownloadPath(row.id), '_blank')
        }
        //  若当前点击项是视频mp4格式
        if (this.VIDEO_TYPE_LIST.includes(row.extension)) {
          let data = {
            visible: true,
            url: this.getDownloadPath(row.id),
            filename: row.filename + '.' + row.extension
          }
          this.$store.commit('setVideoReviewData', data)
        }
        //  若当前点击项是视频mp3格式
        if (this.MUSIC_TYPE_LIST.includes(row.extension)) {
          let data = {
            visible: true,
            url: this.getDownloadPath(row.id),
            filename: row.filename + '.' + row.extension
          }
          this.$store.commit('setVideoReviewData', data)
        }
      }
    },

    /**
     * 表格勾选框事件
     */
    //  表格-全选事件, selectoin 勾选的行数据
    selectAllFileRow(selection) {
      this.$emit('setSelectionFile', selection)
    },
    //  表格-选中一行事件, selectoin 勾选的行数据
    selectFileRow(selection) {
      this.$emit('setSelectionFile', selection)
    },

    /**
     * 移动按钮相关事件
     */
    //  操作列-移动按钮：打开移动文件模态框
    showMoveFileDialog(file) {
      //  第一个参数: 是否批量移动；第二个参数：打开/关闭移动文件模态框
      this.$emit('setOperationFile', file)
      this.$emit('setMoveFileDialogData', false, true)
    },

    //  操作列-解压缩按钮
    unzipFile(fileInfo) {
      const loading = this.$loading({
        lock: true,
        text: '正在解压缩，请稍等片刻...',
        spinner: 'a-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      unzipfile(fileInfo).then(() => {
        this.$emit('getTableDataByType')
        this.$store.dispatch('showStorage')
        this.$message.success('解压成功')
        loading.close()
      }).catch(err => {
        console.log(err)
        this.$message.error("系统忙，解压失败")
      })
    },

    /**
     * 恢复按钮事件
     */
    recoverFileBtn(fileInfo) {
      let data = {
        userFileId: fileInfo.id
      }
      if (this.fileType().isRecycle()) { //  回收站里 - 彻底删除
        this.$confirm('是否恢复该文件?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success'
        }).then(() => {
          recoverRecycleFile(data).then(() => {
              this.$message({
                type: 'success',
                message: filenameComplete(fileInfo) + '已恢复'
              })
              this.$emit('getTableDataByType')
              this.$store.dispatch('showStorage')
              this.$store.dispatch('fetchPathTreeMap')
            }
          )
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消恢复'
          })
        })
      }
    },

    //  操作列-删除按钮
    deleteFileBtn(fileInfo) {
      if (this.fileType().isRecycle()) { //  回收站里 - 彻底删除
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.confirmDeleteFile(fileInfo, true)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      } else {  //  非回收站
        this.$confirm('删除后可在回收站查看, 是否继续删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.confirmDeleteFile(fileInfo, false)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    //  删除文件模态框-确定按钮
    confirmDeleteFile(fileInfo, type) {
      let data = {userFileId: fileInfo.id}
      // if (type) {  //  回收站中删除
      //   deleteRecoveryFile(data).then((res) => {
      //     if (res.success) {
      //       this.$emit('getTableDataByType')
      //       this.$message.success('删除成功')
      //     } else {
      //       this.$message.error("删除失败")
      //     }
      //   })
      // } else {  //  非回收站删除
      deleteDepartFile(data).then((res) => {
        if (res.success) {
          this.$emit('getTableDataByType')
          this.$message.success('删除成功')
        } else {
          this.$message.error("删除失败")
        }
      })
      // }
    },
    // 文件重命名
    renameFile(fileInfo) {
      this.renameFileInfo = fileInfo;
      this.$refs.rename.show(fileInfo);
    },
    renameSuccess() {
      this.$emit('getTableDataByType')
      this.$message.success('重命名成功')
    },
  },
  computed: {
    //  selectedColumnList:判断当前用户设置的左侧栏是否折叠, operaColumnExpand:判断当前用户设置的操作列是否展开
    ...mapGetters(['selectedColumnList', 'operaColumnExpand', 'getFilePath']),
    //  判断当前路径下是否有普通文件
    isIncludeNormalFile() {
      return this.fileList.map((data) => data.dir).includes(false)
    },
    //  判断当前路径下是否有压缩文件
    isIncludeZipRarFile() {
      return (
        this.fileList.map((data) => data.extension).includes('zip') ||
        this.fileList.map((data) => data.extension).includes('rar')
      )
    },
    operaColumnWidth() {
      return this.fileType().isRecycle()
        ? 150 : this.operaColumnExpand
          ? this.isIncludeNormalFile ? 290 : 220 : 100
    },
    hasSelected() {
      return this.selectedRowKeys.length > 0;
    },
  }
}
</script>

<style scoped>
/*.file-table-wrapper*/
/*  margin-top 2px*/

/*  .file-type-0*/
/*    height calc(100vh - 206px) !important*/

/*    >>> .a-table__body-wrapper*/
/*      height calc(100vh - 264px) !important*/

/*  .file-type-6*/
/*    height calc(100vh - 211px) !important*/

/*    >>> .a-table__body-wrapper*/
/*      height calc(100vh - 263px) !important*/

/*  .file-table*/
/*    width 100% !important*/
/*    height calc(100vh - 203px)*/

/*    >>> .a-table__header-wrapper*/
/*      th*/
/*        background $tabBackColor*/
/*        padding 8px 0*/

/*      .a-icon-circle-plus, .a-icon-remove*/
/*        margin-left 6px*/
/*        cursor pointer*/
/*        font-size 16px*/

/*        &:hover*/
/*          color $Primary*/

/*    >>> .a-table__body-wrapper*/
/*      height calc(100vh - 255px)*/
/*      overflow-y auto*/
/*      setScrollbar(10px)*/

/*      td*/
/*        padding 8px 0*/

/*  .img-review-wrapper*/
/*    position fixed*/
/*    top 0*/
/*    right 0*/
/*    bottom 0*/
/*    left 0*/
/*    overflow auto*/
/*    width 100%*/
/*    height 100%*/
/*    z-index 2010*/
/*    text-align center*/
/*    display flex*/
/*    align-items center*/
/*    animation imgReviewAnimation 0.3s*/
/*    -webkit-animation imgReviewAnimation 0.3s !* Safari and Chrome *!*/
/*    animation-iteration-count 0.3*/
/*    -webkit-animation-iteration-count 0.3*/
/*    animation-fill-mode forwards*/
/*    -webkit-animation-fill-mode forwards !* Safari 和 Chrome *!*/
/*    @keyframes imgReviewAnimation*/
/*      0%*/
/*        background transparent*/
/*      100%*/
/*        background rgba(0, 0, 0, 0.8)*/
/*    @keyframes imgReviewAnimation*/
/*      0%*/
/*        background transparent*/
/*      100%*/
/*        background rgba(0, 0, 0, 0.8)*/

/*    .img-large*/
/*      margin 0 auto*/
/*      max-width 80%*/
/*      max-height 100%*/
</style>
